package com.ityun.ogapp.base

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager

/**
 * @author freed
 * @date 2023/1/10 09:04
 * @description TODO
 */
public open class BaseDialogFragment : DialogFragment() {

    override fun onStart() {
        super.onStart()
        val dialog = dialog
        val window = dialog!!.window
        val lp = window!!.attributes
        lp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND
        //        lp.dimAmount = splash; //当FLAG_DIM_BEHIND设置后生效。该变量指示后面的窗口变暗的程度。 1.0表示完全不透明，0.0表示没有变暗。
        lp.gravity = Gravity.CENTER
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT
        window.attributes = lp
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setCanceledOnTouchOutside(true)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        showAllowingStateLoss(manager, tag)
    }

    private fun showAllowingStateLoss(manager: FragmentManager, tag: String?) {
        try {
            val dismissed = DialogFragment::class.java.getDeclaredField("mDismissed")
            dismissed.isAccessible = true
            dismissed[this] = false
        } catch (e: Exception) {
        }
        try {
            val shown = DialogFragment::class.java.getDeclaredField("mShownByMe")
            shown.isAccessible = true
            shown[this] = true
        } catch (e: Exception) {

        }
        val ft = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()
    }
}